﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Net;

namespace AutoIndustryFiles
{
    public partial class Form1 : Form
    {
        List<FileLinksScraper> scrapers = new List<FileLinksScraper> { };
        ExcelWrapper.ExcelApp ea = null;

        bool Cancelled = false;

        public Form1()
        {
            InitializeComponent();
            
            scrapers.Add(new FuJiScraper());
            //scrapers.Add(new abbScraper());

            foreach(FileLinksScraper linkScraper in scrapers)
                linkScraper.OnProcessingEvent += new FileLinksScraper.OnProcessing(linkScraper_OnProcessingEvent);
        }

        void linkScraper_OnProcessingEvent(string className, string msg, ref bool bCancelled)
        {
            foreach (ListViewItem lvi in listView1.CheckedItems)
                if (lvi.Tag.ToString().ToUpper() == className.ToUpper())
                    lvi.SubItems[1].Text = msg;
            bCancelled = Cancelled;
        }

        ~Form1()
        {
            ea = null;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "下载")
            {
                Cancelled = false;
                button1.Text = "取消下载";
                Application.DoEvents();
                foreach (ListViewItem lvi in listView1.CheckedItems)
                {
                    scrapers[lvi.Index].GenerateAllLinks();
                    scrapers[lvi.Index].ExportToExcel(ea,Application.StartupPath + "\\" + lvi.Text + ".xlsx", Application.StartupPath + "\\template.xlsx");
                }
                button1.Text = "下载";
            }
            else
            {
                Cancelled = true;
                button1.Text = "下载";
            }
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            listView1.Columns[1].Width = listView1.Width - listView1.Columns[0].Width - 30;
        }
        List<string> urls500 = new List<string> { };
        int goto_index = 0;
        private void button2_Click(object sender, EventArgs e)
        {
            /*string content = File.ReadAllText(Application.StartupPath + "\\GetDocumentsByDocumentKindAndProductId.txt");

            List<abbDoc> docs = JsonConvert.DeserializeObject<List<abbDoc>>(content);*/
            //List<string> cid = new List<string> { "9AAC174076", "9AAC176189", "9AAC183500", "9AAC167934", "9AAC124466", "9AAC100780", "9AAC100380", "9AAC124522", "9AAC100776", "9AAC210792", "9AAC100810", "9AAC130017", "9AAC100777", "9AAC100225", "9AAC100741", "9AAC124501" };
            //List<string> cid = new List<string> { "9AAC168588", "9AAC100794", "9AAC126040", "9AAC100795", "9AAC100791", "9AAC126055", "9AAC168635", "9AAC168708", "9AAC168718", "9AAC168722", "9AAC168647", "9AAC126041", "9AAC100796", "9AAC124986", "9AAC126054" };
            //List<string> cid = new List<string> { "9AAC111725", "9AAC180396", "9AAC181704", "9AAC176224" };
            //List<string> cid = new List<string> { "9AAC168664", "9AAC100787", "9AAC100786", "9AAC126048", "9AAC100790", "9AAC100789", "9AAC100788", "9AAC126049" };
            //List<string> cid = new List<string> { "9AAC172657", "9AAC100503", "9AAC100486", "9AAC100514", "9AAC100489", "9AAC125911", "9AAC100502", "9AAC125913", "9AAC100490", "9AAC100508", "9AAC100488", "9AAC125910" };
            /*List<string> cid = new List<string> { "9AAC135182",  "9AAC167310", "9AAC167303", "9AAC167309", "9AAC167307", "9AAC167311", "9AAC167313", "9AAC167301", "9AAC166172", "9AAC100090",  "9AAC167291", "9AAC167288", "9AAC167290", "9AAC174111", "9AAC167292", "9AAC167294", "9AAC176637" };

            string url = @"http://www140.abb.com/ABBLibraryUiWebServices/ABBLibraryDownloadSectionService.svc/WebDownloadSection/GetDocumentsByDocumentKindAndProductId?method=&categoryId={0}&languageCode=zh&countryCode=CN&clientCode=abbcom&includeSubcategories=true&documentKind=&source=ds";

            WebFunctions.WebFuncs.OpenUrlEx(string.Format(url, cid[int.Parse(textBox1.Text)]), "UTF-8");
            string url = @"http://www140.abb.com/ABBLibraryUiWebServices/ABBLibraryDownloadSectionService.svc/WebDownloadSection/GetDocumentsByDocumentKindAndProductId?method=&categoryId={0}&languageCode=zh&countryCode=CN&clientCode=abbcom&includeSubcategories=true&documentKind=&source=ds";
            string[] lines = File.ReadAllLines(@"C:\Users\Administrator\Desktop\abb\5000.txt");
            foreach (string s in lines)
            {
                WebFunctions.WebFuncs.OpenUrlEx(string.Format(url, s), "UTF-8");
                Application.DoEvents();
            }*/

            /*abbScraper s = new abbScraper();
            s.OnProcessingEvent += new FileLinksScraper2.OnProcessing(s_OnProcessingEvent);
            s.GenerateAllLinks("pscat");*/

            danfossScraper s = new danfossScraper();
            s.OnProcessingEvent += s_OnProcessingEvent;
            //s.GetDownloadIndex();
            //s.GenerateAllLinks("");
            //ea = new ExcelWrapper.ExcelApp();
            s.Traverse();
            //s.GetDownloadUrls(ea, Application.StartupPath + "\\Output\\yaskawa_urls.xlsx");
            //s.ExportToExcel(ea, Application.StartupPath + "\\Output\\" + s.CompanyName + ".xlsx", Application.StartupPath + "\\template.xlsx");
            //s.GetNamesOfAllProducts();
            //urls500 = s.ProductUrls;
            //timer1.Enabled = true;
            //schneiderDoc doc = s.ReadSchneiderFile(@"C:\ProductsList\011_Acti 9 C120 大额定电流断路\Dump-0513-16-38-23\www.schneider-electric.com\download\filters\ResultGrid.cfc");

            //s.DocsToExcel(ea,@"D:\外包项目\自动化资料下载\Output\schneider\AllDocs.xlsx");
            //s.CatalogDocs(ea, @"D:\外包项目\自动化资料下载\Output\schneider\分类文档.xlsx");
            //s.ExportToExcel(ea, @"D:\外包项目\自动化资料下载\Output\" + s.CompanyName + ".xlsx", Application.StartupPath + "\\template.xlsx");

            //string content = WebFunctions.WebFuncs.OpenUrlEx("http://www.fa.omron.com.cn/products/family/1995/download/catalog.html", "UTF-8");
        }

        void s_OnProcessingEvent(string className, string msg, ref bool bCancel)
        {
            label1.Text = msg;
            Application.DoEvents();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            webBrowser1.Navigate(textBox2.Text);
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ea.Quit();
            ea = null;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (goto_index < urls500.Count)
            {
                System.Diagnostics.Process.Start("chrome.exe", urls500[goto_index]);
                goto_index++;
            }
            else
                timer1.Enabled = false;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            string url = @"http://yaskawa.com.cn/download/";
            Uri uri = new Uri(url);
            CookieContainer cookies = CookieManger.GetUriCookieContainer(uri);
        }
    }

    public class CookieManger
    {
        [DllImport("wininet.dll", SetLastError = true)]
        public static extern bool InternetGetCookie(string url, string cookieName, StringBuilder cookieData, ref int size);

        public static CookieContainer GetUriCookieContainer(Uri uri)
        {
            CookieContainer cookies = null;
            //定义Cookie数据的大小。
            int datasize = 256;
            StringBuilder cookieData = new StringBuilder(datasize);

            if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize))
            {
                if (datasize < 0) return null;
                // 确信有足够大的空间来容纳Cookie数据。
                cookieData = new StringBuilder(datasize);
                if (!InternetGetCookie(uri.ToString(), null, cookieData, ref datasize)) return null;
            }

            if (cookieData.Length > 0)
            {
                cookies = new CookieContainer();
                cookies.SetCookies(uri, cookieData.ToString().Replace(';', ','));
            }
            return cookies;
        }

        public static void PrintCookies(CookieContainer cookies, Uri uri)
        {
            CookieCollection cc = cookies.GetCookies(uri);

            foreach (var cook in cc)
            {
                Console.WriteLine(cook);
            }
        }
    }

}

